#!/usr/bin/python
# -*- coding:utf-8 -*-
from lib.utils.display import Display
from lib.data.ansible_data import Format
from lib.db.mysql import cmdb_hosts as table
import json

display = Display()


class Load(object):
    def __init__(self):
        display.info('Data Format Started.')
        self._data = json.loads(Format().combine)
        for i in self._data:
            print json.dumps(i.get('data').get('core_facts'), indent=4, sort_keys=True)
        self._dicSum = dict(
            sum_total=len(self._data),
            sum_success=0,
            sum_failed=0,
            sum_inserted=0,
            sum_updated=0,
            sum_process=0,
        )
        print self._dicSum
        display.info('Data Format Finished.')

    def run(self):
        # for key, value in self.dicFormalData['data'].items():
        for data in self._data:
            # core_data = data.get('data').get('core_data')
            counts = table().Query(data)
            if counts != 0:
                status = table().Update(data)
                if status == 'success':
                    self._dicSum['sum_success'] += 1
                    self._dicSum['sum_updated'] += 1
                else:
                    self._dicSum['sum_failed'] += 1
                    display.error(
                     'Load Ansible Data to MySQL - error : %s' % data['IP']
                    )
            else:
                status = table().Insert(data)
                if status == 'success':
                    self._dicSum['sum_success'] += 1
                    self._dicSum['sum_inserted'] += 1
                else:
                    self._dicSum['sum_failed'] += 1
                    display.error(
                     'Load Ansible Data to MySQL - error : %s' % data['IP']
                    )
            self._dicSum['sum_process'] += 1
            display.info(
              'Load Ansible Data to MySQL(%s/%s) -- %s -- %s' % (
                self._dicSum['sum_process'],
                self._dicSum['sum_total'],
                data['IP'], status
              )
            )
        return self._dicSum

def main():
    test_load = Load()
    print test_load.run()

if __name__ == '__main__':
    main() 
